package yunhe.factory;

import java.sql.*;
import java.util.List;

/**
 * 单例模式，产生连接的抽象类。 提供connection 关闭statement和resultset
 * 
 * @author lei
 *
 */
public abstract class BaseConn {

	protected static Connection conn = null;

	static { // 单例，保证只产生一个conn对象
		try {
			Class.forName(ConnInfo.DRIVER);
			conn = DriverManager.getConnection(ConnInfo.URL, ConnInfo.USERNAME,
					ConnInfo.PASSWORD);
			conn.setAutoCommit(false);
		} catch (Exception e) {

		}
	}

	/**
	 * 提供关闭的方法
	 * 
	 * @param st
	 * @param rs
	 */
	protected final void closeAll(Statement st, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (st != null) {
				st.close();
			}
		} catch (Exception e) {
			rs = null;
			st = null;
		}
	}

	/**
	 * 设置PreparedStatement的参数
	 * 
	 * @param sql
	 * @param params
	 * @return
	 */
	protected Statement setParams(String sql, Object[] params, int statementType) {
		Statement st = null;
		switch (statementType) {
		case 1:
			// =1,为PreparedStatement
			try {
				PreparedStatement pst = conn.prepareStatement(sql);
				if (params != null) {
					for (int i = 0; i < params.length; i++) {
						pst.setObject(i + 1, params[i]);
					}
				}
				st = pst;

			} catch (Exception e) {
				st = null;
			}
			break;
		case 2:
			// //=2,为CallableStatement
			try {
				CallableStatement cst = conn.prepareCall(sql);
				if (params != null) {
					for (int i = 0; i < params.length; i++) {
						cst.setObject(i + 1, params[i]);
					}
				}
				st = cst;

			} catch (Exception e) {
				st = null;
			}
			break;

		default:
			st = null;
			break;
		}

		return st;

	}

	/**
	 * 通用增删改方法
	 * 
	 * @param sql
	 * @param params
	 * @return
	 */
	protected int CUD(String sql, Object[] params) {
		int row = 0;
		PreparedStatement pst = (PreparedStatement) setParams(sql, params, 1);
		ResultSet rs = null;
		try {
			row = pst.executeUpdate();
			conn.commit();
		} catch (Exception e) {
			row = -1;
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			closeAll(pst, rs);
		}

		return row;
	}


	/**
	 * 批量执行增删改语句
	 * @param sqlModel sql语句模板
	 * @param listParams 参数列表数组
	 * @return
	 */


	protected int CUD(String sqlModel, List<Object[]> listParams) {
		int row = -1;
		for(int i=0;i<listParams.size();i++) {
			PreparedStatement pst = null;
			try {
				pst = (PreparedStatement) setParams(sqlModel, listParams.get(i), 1);
				row = pst.executeUpdate();
			} catch (Exception e) {
				row = -1;
				break;
			} finally {
				closeAll(pst, null);
			}	
		}
		
		try {
			if(row==-1){
				conn.rollback();
			}else{
				conn.commit();	
			}	
		} catch (SQLException e) {
			row = -1;
			e.printStackTrace();
		}
		return row;
	}

	public void close() {
		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static  int name(){
		return 0;
		
	}

}
